package com.study.example.gameserver.module.ranklist;

import com.sparrow.common.handler.HandlerManager;
import com.sparrow.common.thread.IdExecutorGroup;
import com.study.example.gameserver.module.player.entity.Player;
import com.study.example.gameserver.module.ranklist.domain.RankType;
import com.study.example.gameserver.module.ranklist.entity.PlayerRank;
import com.study.example.gameserver.module.ranklist.handler.RankHandler;
import com.study.example.gameserver.module.ranklist.manager.RankManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.function.BiFunction;

@Component
public class RankService {
    @Autowired
    RankManager rankManager;
    @Autowired
    IdExecutorGroup idExecutorGroup;

    private static final String TASK_NAME = "updateRank";

    public RankHandler getHandler(RankType rankType) {
        return HandlerManager.getInstance()
                .getHandler(RankHandler.class, rankType);
    }

    public void updateRank(RankType rankType, Player player, BiFunction<RankType, Player, Object> function) {
        idExecutorGroup.execute(TASK_NAME, rankType.getType(), () -> {
            Object rankData = function.apply(rankType, player);
            PlayerRank playerRank = rankManager.getOrCreateRank(rankType, player.getPlayerId());
            playerRank.setPlayerName(player.getPlayerName());
            playerRank.setRankData(rankData);
            playerRank.update();
            rankManager.updateRank(rankType, playerRank);
        });
    }

}
